import { fetchHome } from '../../services/home/home';
import { fetchGoodsList } from '../../services/good/fetchGoods';
import Toast from 'tdesign-miniprogram/toast/index';
const { testAPI, homeAPI } = require('../../services/api.js');

Page({
  data: {
    imgSrcs: [],
    tabList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'scaleToFill' },
    deliveryInfo : {
      receiverName: "",
      address:"",
      phoneNumber:""
    },
    shopInfo:{
      shopName:"",
      shopAddress:"",
      shopId:""
    },
    residents:[],
    displayResidents: [],
    gridClass: '' // 根据数量动态添加样式
  },

  goodListPagination: {
    index: 0,
    num: 20,
  },

  privateData: {
    tabIndex: 0,
  },

  onShow() {
    this.getTabBar().init();
  },

  onLoad() {
    this.init();
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.loadHomePage();
  },

  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
    });

    
    // 构建请求参数
    const requestParams = {
      customerId: "C2025010100002",
      latitude: 39.9042,    // 可选参数
      longitude: 116.4074,  // 可选参数
      shopId: "SHOP001",    // 可选参数
      categoryId: "CAT001"  // 可选参数
    };
    homeAPI.fetchHomePage(requestParams)
      .then(data => {
        console.log(">>>> 获取到的数据:", data);
        // 在这里使用 data
        const deliveryInfoData =  data.data.deliveryInfo
        const deliveryInfo = {
          receiverName: deliveryInfoData?.name || "设置默认收货人",
          address:deliveryInfoData?.address || "设置默认地址",
          phone: deliveryInfoData?.phone || "设置收货人联系方式"
        }
        
        const shopInfoData = data.data.currShopInfo
        const shopInfo = {
          shopName:shopInfoData.shopName,
          shopAddress:shopInfoData.shopAddress,
          shopId:shopInfoData.shopId
        }
        const tabList = data.data.categoryInfo;

        const residents =  data.data.residentInfo;
        const len = Math.min(residents.length, 6)
        const displayResidents = residents.slice(0, len)
        let gridClass = ''
        if (len <= 3) gridClass = 'grid-3'
        else gridClass = 'grid-3-two-rows'
        this.setData({
          processHomeData: data,
          loading: false,
          deliveryInfo,
          shopInfo,
          tabList,
          residents,
          displayResidents,
          gridClass,
          pageLoading: false,
        });

        this.loadGoodsList(true);
      })
      .catch(error => {
        console.error("获取首页数据失败:", error);
        this.setData({
          error: error.message || '加载失败',
          loading: false
        });
      });
  },

  tabChangeHandle(e) {
    this.privateData.tabIndex = e.detail;
    console.log("tabChangeHandle:"+ JSON.stringify(this.privateData.tabIndex));
    this.loadGoodsList(true);
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }

    this.setData({ goodsListLoadStatus: 1 });

    const pageSize = this.goodListPagination.num;
    let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;
    if (fresh) {
      pageIndex = 0;
    }

    try {
      const nextList = await fetchGoodsList(pageIndex, pageSize);
      this.setData({
        goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
        goodsListLoadStatus: 0,
      });

      this.goodListPagination.index = pageIndex;
      this.goodListPagination.num = pageSize;
    } catch (err) {
      this.setData({ goodsListLoadStatus: 3 });
    }
  },

  onRightButtonClick(e){
    // const {index} = 2;
    // const { spuId } = 135681624;
    // wx.navigateTo({
    //   url: `/pages/goods/details/index?spuId=${spuId}`,
    // });

    this.testConnection();

  },
// 测试连接
  async testConnection() {
    try {
      const res = await testAPI.hello();


      this.setData({
        message: res.data
      });

      wx.showToast({
        title: res.data,
        icon: 'success'
      });
    } catch (error) {
      console.error('连接测试失败:', error);
      wx.showToast({
        title: '连接失败',
        icon: 'none'
      });
    }
  },
  goodListClickHandle(e) {
    const { index } = e.detail;
    const { spuId } = this.data.goodsList[index];
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}`,
    });
  },

  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },

  navToSearchPage() {
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },

  navToActivityDetail({ detail }) {
    const { index: promotionID = 0 } = detail || {};
    wx.navigateTo({
      url: `/pages/promotion/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },
});
